<template>
  <div class="read-message">
    <div v-if="loading" class="loading">
      加载中...
    </div>
    <div v-else-if="error" class="error">
      {{ error }}
    </div>
    <div v-else-if="needPassword" class="password-form">
      <h2>此消息受密码保护</h2>
      <div class="password-input">
        <input 
          type="password" 
          v-model="password"
          placeholder="请输入访问密码"
          @keyup.enter="verifyPassword"
        >
      </div>
      <button @click="verifyPassword" class="verify-btn">验证密码</button>
      <p v-if="passwordError" class="error-text">{{ passwordError }}</p>
    </div>
    <div v-else-if="message" class="message-content">
      <h2>{{ message.title || '私密消息' }}</h2>
      <div class="message-box">
        <p v-if="message.content">{{ message.content }}</p>
        <div v-if="message.image" class="image-container">
          <img :src="message.image" alt="消息图片" />
        </div>
      </div>
      <p class="warning">此消息已读，下次访问将无法查看！</p>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, watch } from 'vue';
import { useRoute } from 'vue-router';
import axios from 'axios';
import { config } from '../config';

export default {
  name: 'ReadMessage',
  setup() {
    const route = useRoute();
    const message = ref(null);
    const loading = ref(true);
    const error = ref(null);
    const needPassword = ref(false);
    const password = ref('');
    const passwordError = ref(null);

    // 更新页面标题
    const updatePageTitle = (msg) => {
      if (msg && msg.title) {
        document.title = msg.title;
      } else {
        document.title = '私密消息';
      }
    };

    // 监听消息变化以更新标题
    watch(message, (newMsg) => {
      updatePageTitle(newMsg);
    });

    const checkPasswordProtection = async () => {
      try {
        const response = await axios.get(
          `${config.BACKEND_API_URL}/${route.params.accessKey}/protected`
        );
        needPassword.value = response.data.protected;
        if (!needPassword.value) {
          fetchMessage();
        }
      } catch (err) {
        handleError(err);
      } finally {
        loading.value = false;
      }
    };

    const verifyPassword = async () => {
      try {
        passwordError.value = null;
        const response = await axios.post(
          `${config.BACKEND_API_URL}/${route.params.accessKey}/verify`,
          { password: password.value }
        );
        if (response.data.valid) {
          fetchMessage();
        } else {
          passwordError.value = '密码错误，请重试';
        }
      } catch (err) {
        handleError(err);
      }
    };

    const fetchMessage = async () => {
      try {
        loading.value = true;
        const response = await axios.get(
          `${config.BACKEND_API_URL}/${route.params.accessKey}`,
          { params: { password: password.value } }
        );
        message.value = response.data;
        needPassword.value = false;
      } catch (err) {
        handleError(err);
      } finally {
        loading.value = false;
      }
    };

    const handleError = (err) => {
      console.error('Error:', err);
      if (err.response?.data?.message) {
        error.value = err.response.data.message;
      } else {
        error.value = '消息加载失败，请稍后重试';
      }
      document.title = '消息不存在或已被删除';
    };

    onMounted(() => {
      checkPasswordProtection();
    });

    return {
      message,
      loading,
      error,
      needPassword,
      password,
      passwordError,
      verifyPassword,
    };
  },
};
</script>

<style scoped>
.read-message {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.loading {
  text-align: center;
  padding: 20px;
}

.error {
  color: #ff4444;
  text-align: center;
  padding: 20px;
}

.password-form {
  background-color: #f5f5f5;
  padding: 20px;
  border-radius: 4px;
  text-align: center;
}

.password-input {
  margin: 15px 0;
}

.password-input input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.verify-btn {
  background-color: #4CAF50;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.verify-btn:hover {
  background-color: #45a049;
}

.error-text {
  color: #ff4444;
  margin-top: 10px;
  font-size: 0.9em;
}

.message-content {
  background-color: #f5f5f5;
  padding: 20px;
  border-radius: 4px;
}

.message-box {
  background-color: white;
  padding: 15px;
  border-radius: 4px;
  margin: 15px 0;
}

.message-box p {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.image-container {
  margin-top: 15px;
}

.image-container img {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.warning {
  color: #ff4444;
  font-size: 0.9em;
  margin-top: 15px;
  text-align: center;
}
</style>
